from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from google.appengine.api import users
from google.appengine.ext import db

import models

###########################################################################################################################
def render(template, payload):
    '''render the template with payload'''
    return render_to_response(template, payload)

def logUserAccess(user):
    '''log the user access to data store'''
    usr = models.User.all().filter('user = ', user).get()
    if not usr:
        usr = models.User(user=user, access_count=1)
    else:
        if usr.access_count:
            usr.access_count = usr.access_count + 1
        else:
            usr.access_count = 1 + 1
        
    usr.put()

def getAllUsers():
    '''get all the users order by the last access'''
    return models.User.all().order('-last_update')

def getUser(email="anonymous@gmail.com"):
    '''get all the current user, if not exist, return anonymous'''
    user = users.get_current_user()
    if not user:
        user = users.User(email)
    logUserAccess(user)
    return user

def getLoginAndUrl(request):
    '''get toggled login and logout label and the url'''
    if users.get_current_user():
        url = users.create_logout_url(request.get_full_path())
        url_linktext = 'Logout'
    else:
        url = users.create_login_url(request.get_full_path())
        url_linktext = 'Login'
    return url_linktext, url

def logActivity():
    pass
    

###########################################################################################################################
# /chat/
# GET
def index(request):
    user = getUser()
    msgs = models.Message.all().filter('author = ', user).order('-created_on').fetch(10)
    
    clss = models.Classification.all()
    
    url_linktext, url = getLoginAndUrl(request)
    
    payload = {'msgs': reversed(msgs), 'clss': clss, 'url_linktext': url_linktext, 'url': url, 'user' : user, 'usrs': getAllUsers(), }
    
    return render('chat_index.html', payload)
    
###########################################################################################################################
# /chat/add/
# POST
# *message : message of the Message
# *email : email of the current User
def add(request):
    message = request.POST['message']
    email = request.POST['email']
    message = message.rstrip()
    
    message = unicode(message, 'utf-8')
    #message = urllib.unquote(message)
    
    if not message or message == "":
        return None
    
    msg = models.Message(message=message, author=getUser(email))
    msg.put()

    clss = models.Classification.all()
    #return HttpResponse(msg.htmlMsg())
    payload = {'msg': msg, 'clss': clss, }
    return render('chat_item.html', payload)
    
###########################################################################################################################
# /chat/update/
# POST
# *msgkey : key of the last Message
# *clskey : key of the Classificaiton
def update(request):
    msgkey = request.POST['msgkey']
    clskey = request.POST['clskey']
    
    user = getUser()
    msgs = models.Message.all().filter('author = ', user)
    
    if msgkey and msgkey != "None":
        lastmsg = models.Message.get(msgkey)
        if lastmsg:
            msgs = msgs.filter('created_on > ', lastmsg.created_on)
        
    if clskey and clskey != "None":
        cls = models.Classification.get(clskey)
        if cls:
            msgs = msgs.filter('classification = ', cls)
        
    msgs = msgs.order('created_on')
    
    payload = {'msgs': msgs, }
    
    return render('chat_items.html', payload)
    
###########################################################################################################################
# /chat/addclass/
# POST
# *name : name of the Classification
# *iconcolor : iconcolor of the Classification
def addclass(request):
    user_email = getUser().email()
    if user_email == "ldmiao@gmail.com" or user_email == "zhaoyong04@gmail.com":
        name = request.POST['name']
        iconcolor = request.POST['iconcolor']
        #description = request.POST['description']
        cls = models.Classification(name=name, iconcolor=iconcolor)
        cls.put()
        
        payload = {'cls': cls, }
        return render('class_item.html', payload)
    return HttpResponse("error!"+"Sorry, You are not authorized to do this.")
    
###########################################################################################################################
# /chat/mark/
# POST
# *msgkey : key of the Message
# *clskey : key of the Classificaiton
def mark(request):
    msgkey = request.POST['msgkey']
    msg = db.get(msgkey)
    
    if msg.author == getUser():
        clskey = request.POST['clskey']
        cls = db.get(clskey)
        
        msg.classification = cls
        msg.put()
        
        return HttpResponse(str(msg.key())+","+cls.iconcolor)
    else:
        return HttpResponse("error!"+"Sorry, You are not authorized to do this.")
        
###########################################################################################################################
# /chat/edit/
# POST
# *msgkey : key of the Message
# *message : message of the Message
def edit(request):
    msgkey = request.POST['msgkey']
    msg = models.Message.get(msgkey)
    
    if msg.author == getUser():
        message = request.POST['message']
        message = unicode(message, 'utf-8')
        msg.message = message
        msg.put()
        
        return HttpResponse(msgkey+","+msg.htmlMsg())
    else:
        return HttpResponse("error!"+"Sorry, You are not authorized to do this.")

###########################################################################################################################